package cn.simonfish.carrier.common.freemarker;

import cn.simonfish.carrier.common.Dict;
import com.jfinal.template.TemplateException;
import freemarker.core.Environment;
import freemarker.ext.beans.StringModel;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateModel;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

/**
 * <@mapping dict='order.status' key='' ></@mapping>
 * Created by simon on 2017/9/19.
 */
public class DictMappingDirective implements TemplateDirectiveModel {

    public void execute(Environment env, Map map, TemplateModel[] templateModels, TemplateDirectiveBody body)
            throws TemplateException, IOException {
        String dict = map.get("dict").toString();
        Object key = map.get("key");
        Map dictMap = (Map)Dict.get(dict);
        Writer out = env.getOut();
        out.append(dictMap.get(key)+"");
        out.flush();
    }


    protected <T> T getParam(Map map,String key,Class<T> clz){
        Object object = getParam(map,key);
        if(object!=null){
            return clz.cast(object);
        }else{
            return  null;
        }
    }

    protected Object getParam(Map map,String key){
        Object val = map.get(key);
        if (val != null){
            StringModel model = (StringModel)val;
            return model.getWrappedObject();
        }else{
            return null;
        }
    }
}
